var config = require("../config");
//引入redis
var redis = require("redis");
//创建redis客户端

const getClient = () => {
  let success = true;
  const client = redis.createClient(config.redis.port, config.redis.host);
  //连接错误处理
  client.on("error", function(error) {
    console.log(error);
    success = false;
  });
  if (success) {
    //redis验证 （如果redis没有开启验证，此配置可以不写）
    client.auth(config.redis.auth);
    //查找
    return client;
  } else {
    return undefined;
  }
};

const getValue = key => {
  return new Promise((resolve, reject) => {
    let client = getClient();
    if (client) {
      client.get(key, (error, res) => {
        if (error) {
          console.log(error);
          reject(error);
          return;
        }
        return resolve(res);
        //操作完成，关闭redis连接
        client.end(true);
      });
    } else {
      reject({
        message: "redis error"
      });
    }
  });
};
const setValue = (key, value) => {
  return new Promise((resolve, reject) => {
    let client = getClient();
    if (client) {
      client.set(key, value, (error, res) => {
        if (error) {
          console.log(error);
          reject(error);
          return;
        }
        return resolve(res);
        //操作完成，关闭redis连接
        client.end(true);
      });
    } else {
      reject({
        message: "redis error"
      });
    }
  });
};
const delKey = key => {
  return new Promise((resolve, reject) => {
    let client = getClient();
    if (client) {
      client.del(key, (error, res) => {
        if (error) {
          console.log(error);
          reject(error);
          return;
        }
        return resolve(res);
        //操作完成，关闭redis连接
        client.end(true);
      });
    } else {
      reject({
        message: "redis error"
      });
    }
  });
};

exports.getValue = getValue;
exports.setValue = setValue;
exports.delKey = delKey;
